package me.zhengjie.modules.utils;

import me.zhengjie.modules.transformer.domain.FdsData;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * CSVScanner
 *
 * @author weiruitao
 * @date 2021/11/30
 */
@Component
public class CSVUtils {

    private static Integer batch = 1;

    public List<List<String>> getData(File file) {
        return getData(file, "");
    }

    public List<List<String>> getData(File file, String field) {

        String line = "";
        final String delimiter = ",";
        List<List<String>> data = new ArrayList<>();
        try {
            FileReader fileReader = new FileReader(file);

            BufferedReader reader = new BufferedReader(fileReader);
            boolean startScan = false;
            while ((line = reader.readLine()) != null) {
                String[] token = line.split(delimiter);
                if (token.length == 0) startScan = false;
                if (startScan) {
                    data.add(Arrays.asList(token));
//                    System.out.println(Arrays.toString(token));
                }
                if (token.length != 0 && token[0].equals(field)) startScan = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }

    public List<FdsData> packingFdsData(List<List<String>> data) {
        List<FdsData> fds = new ArrayList<>();
        System.out.println("fds size: " + data.size());
        data.remove(0);
        for (List<String> datum : data) {
            if (datum.size() == 0) continue;
            FdsData fdsData = new FdsData(batch, batch, datum.get(1), datum.get(2), datum.get(3), datum.get(4), datum.get(5), datum.get(6), datum.get(7));
            fds.add(fdsData);
        }
        batch++;
        return fds;
    }

//    public static void main(String[] args) {
//        List<List<String>> data = getData("C:\\D盘\\Desktop\\2021.1.14 40度 5.21%与4.16%受潮 新绝缘纸2块 无撑条隔开.csv", "[FDSData]");
//        System.out.println(data);
//    }
}
